﻿using System.Data;
using System.Data.Entity;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;

namespace Archie.Retail.Data.SqliteStorage
{
    internal class ArchieRetailContext : DbContext
    {
        public DbSet<Door> Doors { get; set; }
        public DbSet<DoorManufacturer> DoorManufacturers { get; set; }
        public DbSet<DoorSeries> DoorSeries { get; set; }
        public DbSet<Handle> Handles { get; set; }
        public DbSet<HandleSeries> HandleSeries { get; set; }

        public ArchieRetailContext()
            : base("ArchieRetailContext")
        {

        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Door>().HasRequired(d => d.DoorManufacturer);
            modelBuilder.Entity<Door>().HasRequired(d => d.DoorSeries);
        }

        public void CheckTables()
        {
            // проверяем созданы ли таблицы в БД (провайдер Sqlite не поддерживает создание таблиц при CodeFirst)
            try
            {
                var doorsCount = Doors.Count();
                var doorManufacturersCount = DoorManufacturers.Count();
                var doorSeriesCount = DoorSeries.Count();
                var handlesCount = Handles.Count();
                var handleSeriesCount = HandleSeries.Count();
            }
            catch (EntityCommandExecutionException ex)
            {
                CreateTables(Database.Connection.ConnectionString);
            }
        }

        public static void CreateTables(string connectionString)
        {
            const string whereIsTablesBackup = "TablesCreation.sql";

            using (var connection = new SQLiteConnection(connectionString))
            using (var command = connection.CreateCommand())
            {
                var commandText = GetEmbeddedResourceFromProjectAsString(whereIsTablesBackup);

                command.CommandText = commandText;
                connection.Open();
                command.ExecuteNonQuery();
            }
        }

        // resource format: {folder}.{folder}.{File.txt}
        private static string GetEmbeddedResourceFromProjectAsString(string resourcePath)
        {
            string commandText;
            var thisAssembly = Assembly.GetExecutingAssembly();
            var resourceLocation = string.Format("{0}.{1}", thisAssembly.GetName().Name, resourcePath);
            using (var stream = thisAssembly.GetManifestResourceStream(resourceLocation))
            {
                if (stream == null)
                {
                    throw new MissingManifestResourceException("Resource not found");
                }

                using (var sr = new StreamReader(stream))
                {
                    commandText = sr.ReadToEnd();
                }
            }
            return commandText;
        }

    }
}
